package com.atguigu.jinx.conf;

import com.atguigu.jinx.utils.R;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

/**
 * @author kuangqi
 * @email stevekwong@126.com
 * @date 2024/5/29
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private Gson gson;

    @Override
    @SneakyThrows
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
        httpServletResponse.setContentType("application/json");

        httpServletResponse.getWriter().println(gson.toJson(R.unAuthorized("请您先登陆")));
        httpServletResponse.getWriter().flush();
    }
}

